package com.xc.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xc.media.mapper.MediaFilesMapper;
import com.xc.media.mapper.MediaProcessHistoryMapper;
import com.xc.media.mapper.MediaProcessMapper;
import com.xc.media.model.po.MediaFiles;
import com.xc.media.model.po.MediaProcess;
import com.xc.media.model.po.MediaProcessHistory;
import com.xc.media.service.MediaFileProcessService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * description MediaFileProcess接口实现
 */
@Slf4j
@Service
public class MediaFileProcessServiceImpl implements MediaFileProcessService {

    @Autowired
    private MediaProcessMapper mediaProcessMapper;

    @Autowired
    private MediaFilesMapper mediaFilesMapper;

    @Autowired
    private MediaProcessHistoryMapper mediaProcessHistoryMapper;

    /**
     * @param shardIndex 分片序号
     * @param shardTotal 分片总数
     * @param count      获取记录数
     * @return java.util.List<com.xc.media.model.po.MediaProcess>
     * @description 获取待处理任务
     */
    @Override
    public List<MediaProcess> getMediaProcessList(int shardIndex, int shardTotal, int count) {
        List<MediaProcess> mediaProcesses = mediaProcessMapper.selectListByShardIndex(shardIndex, shardTotal, count);

        return mediaProcesses;
    }

    // 开启任务实现如下
    public boolean startTask(long id) {
        int result = mediaProcessMapper.startTask(id);
        return result <= 0 ? false : true;
    }

    /**
     * @param taskId   任务id
     * @param status   任务状态
     * @param fileId   文件id
     * @param url      url
     * @param errorMsg 错误信息
     * @description 保存任务结果
     */
    @Override
    public void saveProcessFinishStatus(Long taskId, String status, String fileId, String url, String errorMsg) {
        // 需要更新的任务
        MediaProcess mediaProcess = mediaProcessMapper.selectById(taskId);
        if (mediaProcess == null) {
            log.debug("更新任务状态时，此任务：{}，为空", taskId);
            return;
        }

        LambdaQueryWrapper<MediaProcess> queryWrapper = new LambdaQueryWrapper<MediaProcess>().eq(MediaProcess::getId, taskId);
        // 如果任务执行失败
        if (status.equals("3")) {
            log.debug("任务失败：{}", taskId);
            // 更新MediaProcess表的状态
            MediaProcess mediaProcess_u = new MediaProcess();
            mediaProcess_u.setStatus("3");
            mediaProcess_u.setErrormsg(errorMsg);
            mediaProcess_u.setFinishDate(LocalDateTime.now());
            mediaProcessMapper.update(mediaProcess_u, queryWrapper);
            return;
        }

        //======如果任务执行成功======
        //文件表记录
        if ("2".equals(status)) {
            MediaFiles mediaFiles = mediaFilesMapper.selectById(fileId);
            // 更新media_file表中url
            mediaFiles.setUrl(url);
            mediaFilesMapper.updateById(mediaFiles);

            // 更新MediaProcess表中的状态
            mediaProcess.setStatus("2");
            mediaProcess.setFinishDate(LocalDateTime.now());
            mediaProcess.setUrl(url);
            mediaProcessMapper.update(mediaProcess, queryWrapper);

            // 将MediaProcess表记录插入到MediaProcessHistory表
            MediaProcessHistory mediaProcessHistory = new MediaProcessHistory();
            // 两张表的属性完全一致，直接拷贝
            BeanUtils.copyProperties(mediaProcess, mediaProcessHistory);
            try {
                // 向历史处理表新增数据
                mediaProcessHistoryMapper.insert(mediaProcessHistory);
                // 同时删除待处理任务表中的数据
                mediaProcessMapper.deleteById(taskId);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("任务数据入库异常：{}", e);
            }
        }
    }
}
